package com.xdjmall.service.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.junit.jupiter.api.Test;

import com.xdjmall.dao.CategoryDao;
import com.xdjmall.dao.impl.CategoryDaoImpl;
import com.xdjmall.entity.Category;
import com.xdjmall.service.CategoryService;
import com.xdjmall.servlet.vo.IndexCategoryVO;
import com.xdjmall.servlet.vo.SecondLevelCategoryVO;
import com.xdjmall.servlet.vo.ThirdLevelCategoryVO;
import com.xdjmall.util.QueryCondition;

public class CategoryServiceImpl implements CategoryService {

	private CategoryDao dao = new CategoryDaoImpl();
	
	@Override
	public List<IndexCategoryVO> getCategoriesForIndex() throws SQLException {
		List<IndexCategoryVO> list = new ArrayList<IndexCategoryVO>();
		// 1.通过dao查询所有一级的类别
		QueryCondition condition = new QueryCondition();
		condition.put("categoryLevel", 1);
		List<Category> firstVOs = dao.selectCategoryList(condition);
		//2. 开始倒腾
		firstVOs.forEach(vo->{
			IndexCategoryVO icv = new IndexCategoryVO();
			icv.setCategoryId(vo.getCategoryId());
			icv.setCategoryName(vo.getCategoryName());
			icv.setCategoryLevel(vo.getCategoryLevel());
			//准备二级集合
			List<SecondLevelCategoryVO> secondLevelCategoryVOs = new ArrayList<>();
			QueryCondition condition2 = new QueryCondition();
			condition2.put("categoryLevel", 2);
			condition2.put("parentId", vo.getCategoryId());
			try {
				List<Category> secondVOs = dao.selectCategoryList(condition2);
				secondVOs.forEach(svo -> {
					SecondLevelCategoryVO scv = new SecondLevelCategoryVO();
					scv.setCategoryId(svo.getCategoryId());
					scv.setCategoryLevel(svo.getCategoryLevel());
					scv.setCategoryName(svo.getCategoryName());
					scv.setParentId(svo.getParentId());
					// 三级集合
					List<ThirdLevelCategoryVO> thirdLevelCategoryVOs = new ArrayList<>();
					QueryCondition condition3 = new QueryCondition();
					condition3.put("categoryLevel", 3);
					condition3.put("parentId", svo.getCategoryId());
					try {
						List<Category> thirdVOs = dao.selectCategoryList(condition3);
						thirdVOs.forEach(tvo -> {
							ThirdLevelCategoryVO tcv = new ThirdLevelCategoryVO();
							tcv.setCategoryId(tvo.getCategoryId());
							tcv.setCategoryLevel(tvo.getCategoryLevel());
							tcv.setCategoryName(tvo.getCategoryName());
							tcv.setParentId(tvo.getParentId());
							thirdLevelCategoryVOs.add(tcv);
						});
						scv.setThirdLevelCategoryVOS(thirdLevelCategoryVOs);
					} catch (SQLException e) {
						e.printStackTrace();
					}
					secondLevelCategoryVOs.add(scv);
				});
				icv.setSecondLevelCategoryVOS(secondLevelCategoryVOs);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			list.add(icv);
		});
		return list;
	}

}
